<?php

class RestRequest{

	private $log;
	private $url,$body, $method, $timeout, $acceptType;
	private $curl;
	private $responseInfo, $responseBody;
	private $header;

	public function __construct ($url = null, $method = 'GET', $body = null){
		$this->log = new Logger("RestRequest", _LOGPATH_);
		$this->log->setLogLevel(Logger::VERBOSE);
		$this->url		= $url;
		$this->method 	= $method;
		$this->curl  	= curl_init();
		$this->timeout	= 10;
		$this->acceptType = "";
	}

	public function __destruct(){
		curl_close($this->curl);
	}

	public function send(){
		$this->setCurlOptions();
		$this->log->verbose("Sending curl request...");
		$responseInfo = curl_getinfo($this->curl);
		if(($responseBody = curl_exec($this->curl))===FALSE){
			$this->log->error("curl_exec() fehlgeschlagen");
			$this->log->error("url:$this->url method:$this->method");
			$this->log->error(curl_error($this->curl));
			return false;
		}
		$this->responseInfo	= curl_getinfo($this->curl);
		$this->responseBody = curl_exec($this->curl);
		$this->log->verbose("...successful!");
		return true;
	}

	public function setPostValues($data_array){
		if(is_array($data_array)){
			curl_setopt($this->curl, CURLOPT_POST ,count($data_array));
			curl_setopt($this->curl, CURLOPT_POSTFIELDS,http_build_query($data_array));
		}
	}

	public function setHeader($header){
		if(is_array($header)){
			array_merge($this->header, $header);
		}else{
			$this->header[] = $header;
		}
	}

	private function setCurlOptions(){
		curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->timeout);
		curl_setopt($this->curl, CURLOPT_URL, $this->url);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($this->curl, CURLOPT_HTTPHEADER,$this->header);
		curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
	}


	//GETTER und SETTER
	public function setTimeout($timeout){
		$this->timeout = $timeout;
	}


	public function getResponseInfo($key){
		if(isset($this->responseInfo[$key])){
			return $this->responseInfo[$key];
		}else{
			return null;
		}
	}

	public function getResponseBody(){
		return $this->responseBody;
	}


}